package com.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.web.servlet.bean.UserInfo;
import com.web.servlet.dao.DBConnect;
import com.web.servlet.manager.DaoManager;
/**
 * 用户注册 
 * @author davie.yu
 *
 */
public class RegisterUserServlet extends HttpServlet {
	private static final long serialVersionUID = 8065859586616092880L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request,response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		response.setContentType("text/plain");
		response.setCharacterEncoding("utf-8");
		
		PrintWriter out = response.getWriter();
		
		String userName =request.getParameter("userName");
		String userPassword =request.getParameter("userPassword");
		String userNike =request.getParameter("userNike");
		userNike = new String(userNike.getBytes("iso-8859-1"), "utf-8");
		
		String strIp = request.getRemoteAddr();
		
	    
	    if(userName!=null && userPassword!=null &&userNike!=null){
	    	
	    	if(null != DaoManager.getUserInfoDao().getUserInfoByName(userName)){
	    		RegisterFail(out,"用户名已经存在,请重新注册");
	    		out.flush();
	    		out.close();
	    		return;
	    	}
	    	UserInfo userInfo = new UserInfo();
	    	userInfo.initUser(userName, userPassword, userNike);
	    	userInfo = DaoManager.getUserInfoDao().addUserInfo(userInfo);

			Document document = DocumentHelper.createDocument();
			Element rootElement = document.addElement("user");
			rootElement.addAttribute("st", "success");
			out.print(document.asXML());
	    }
	    else{
	    	RegisterFail(out,"注册信息不能为空");
	    }
		out.flush();
		out.close();
	}

	
	private void RegisterFail(PrintWriter out,String desc)
	{
		Document document = DocumentHelper.createDocument();
    	Element rootElement = document.addElement("user");
    	rootElement.addAttribute("st", "false");
    	rootElement.addAttribute("dc", desc);
    	out.print(document.asXML());
		
	}

}
